package com.genesis.yunnanji.utils;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.genesis.yunnanji.bean.PersonBean;

import org.xutils.ex.DbException;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 和讯工具类
 *
 * @author MoXinA
 */
// TODO: 2017/8/23 和讯工具 
public class GenesisUtils {
    private static GenesisUtils genesisUtils;
    private SPUtils spUtils;
//    private DbUtils dbUtils;


    private Context context;

    private final String dbName = "GenesisDb";

    private GenesisUtils() {

    }


    /**
     * 初始化和讯工具类
     *
     * @param context
     */
    public void init(Context context) {
        this.context = context;
        spUtils = SPUtils.getIntance(context);
//        dbUtils = DbUtils.create(context, dbName);

    }


    public static GenesisUtils getIntance() {
        if (genesisUtils == null) {
            genesisUtils = new GenesisUtils();
        }
        return genesisUtils;
    }

    /**
     * 是否是第一次进入
     *
     * @return
     */
    public boolean isFirst() {
        return spUtils.getBoolean("isFirst", true);
    }

    public void setIsFirst(boolean isFirst) {
        spUtils.setBoolean("isFirst", isFirst);
    }


    /**
     * 保存搜索历史记录
     *
     * @param keyword
     */
    public void setSearchHistory(String keyword) {
        spUtils.putString("key_search_history_keyword", keyword);
    }

    /**
     * 获取搜索历史记录
     *
     * @return
     */
    public String getSearchHistory() {
        return spUtils.getString("key_search_history_keyword", "");
    }

    /**
     * TextView 设置非空文本
     *
     * @param textView
     * @param text
     */
    public void setNotNullText(TextView textView, String text, Boolean isgone) {
        if (!TextUtils.isEmpty(text) && text != null && !text.equals(null)) {
            textView.setText(Html.fromHtml(text.replaceAll("\r\n", "<br>")));
        } else {
            if (isgone == false) {
                textView.setText("暂无资料");
            } else {
                textView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 创建表
     */
//    public void dbCreateTableIfNotExist(Class<?> entiyType) {
//        try {
//            dbUtils.createTableIfNotExist(EaseUser.class);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }
//    public void saveOrUpdate(Object entity) {
//        try {
//            dbUtils.saveOrUpdate(entity);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void saveOrUpdates(Object entity) {
//        try {
//            dbUtils.saveOrUpdate(entity);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void dbsave(Object entity) {
//        try {
//            dbUtils.save(entity);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void dropTable(Class<?> entiyType) {
//        try {
//            dbUtils.dropTable(entiyType);
//        } catch (DbException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 更新数据
//     */
//    public void dbReplace(Object entity) {
//        try {
//            dbUtils.replace(entity);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 查询全部数据
//     *
//     * @param entiyType
//     * @return
//     */
//    public List<?> DbfindAll(Class<?> entiyType) {
//        try {
//            return dbUtils.findAll(entiyType);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


    /**
     * 设置是否已完善资料
     */
    public void setIsCompletedProfile(boolean isCompleted) {
        spUtils.putBoolean("isCompletedProfile", isCompleted);
    }

    /**
     * 是否已完善资料
     *
     * @return
     */
    public boolean isCompletedProfile() {
        return spUtils.getBoolean("isCompletedProfile", false);
    }

    /**
     * @param
     */
    public void setAppToken(String apptoken) {
        spUtils.putString("apptoken", apptoken);
    }

    public String getAppToken() {
        return spUtils.getString("apptoken", "");
    }

    public void setIssetpwd(int issetpwd) {
        spUtils.putInt("issetpwd", issetpwd);
    }

    public int getIssetpwd() {
        return spUtils.getInt("issetpwd", -1);
    }

    public void setCustomConnect(String pla) {
        spUtils.putString("customconnect", pla);
    }

    public String getCustomConnect() {
        return spUtils.getString("customconnect", "");
    }


    /**
     * 保存用户资料
     */
    public void setUserProfile(PersonBean user) {
        spUtils.putString("id", user.getResult().getInfo().getId());
        spUtils.putString("username", user.getResult().getInfo().getUsername());
        spUtils.putString("nickname", user.getResult().getInfo().getNickname());
        spUtils.putString("sex", user.getResult().getInfo().getSex());
        spUtils.putString("photo", user.getResult().getInfo().getPhoto());
        spUtils.putString("birthday", user.getResult().getInfo().getBirthday());
        spUtils.putString("mobile", user.getResult().getInfo().getMobile());
        spUtils.putString("mobile_status", user.getResult().getInfo().getMobile_status());
        spUtils.putString("email", user.getResult().getInfo().getEmail());
        spUtils.putString("email_status", user.getResult().getInfo().getEmail_status());
        spUtils.putString("login_time", user.getResult().getInfo().getLogin_time());
        spUtils.putString("login_ip", user.getResult().getInfo().getLogin_ip());
        spUtils.putInt("connect_qq", user.getResult().getInfo().getConnect_qq());
        spUtils.putInt("connect_weixin", user.getResult().getInfo().getConnect_weixin());
        spUtils.putInt("issetpwd", user.getResult().getInfo().getIssetpwd());
    }

    /**
     * 获取用户资料
     *
     * @return
     */
    public PersonBean getUserProfile() {
        PersonBean profile = new PersonBean();
        PersonBean.ResultBean resultBean = new PersonBean.ResultBean();
        PersonBean.ResultBean.InfoBean infoBean = new PersonBean.ResultBean.InfoBean();
        infoBean.setId(spUtils.getString("id", ""));
        infoBean.setUsername(spUtils.getString("username", ""));
        infoBean.setNickname(spUtils.getString("nickname", ""));
        infoBean.setSex(spUtils.getString("sex", ""));
        infoBean.setPhoto(spUtils.getString("photo", ""));
        infoBean.setBirthday(spUtils.getString("birthday", ""));
        infoBean.setMobile(spUtils.getString("mobile", ""));
        infoBean.setMobile_status(spUtils.getString("mobile_status", ""));
        infoBean.setEmail(spUtils.getString("email", ""));
        infoBean.setEmail_status(spUtils.getString("email_status", ""));
        infoBean.setLogin_time(spUtils.getString("login_time", ""));
        infoBean.setLogin_ip(spUtils.getString("login_ip", ""));
        infoBean.setConnect_qq(spUtils.getInt("connect_qq", -1));
        infoBean.setConnect_weixin(spUtils.getInt("connect_weixin", -1));
        infoBean.setIssetpwd(spUtils.getInt("issetpwd", -1));
        resultBean.setInfo(infoBean);
        profile.setResult(resultBean);
        return profile;
    }

    /**
     * 保存用户头像
     *
     * @param url
     */
    public void setUserImage(String url) {
        spUtils.putString("user_image", url);
    }

    public String getUserImage() {
        return spUtils.getString("user_image", "");
    }

    /**
     * 获取用户名
     *
     * @return
     */
//    public String getUserName() {
//        return spUtils.getString("userName", "");
//   }

    /**
     * 保存用户openid
     *
     * @param openidStr
     */
//    public void setUserOpenId(String openidStr) {
//        spUtils.putString("openid", openidStr);
//    }

//    public String getUserOpenId() {
//        return spUtils.getString("openid", "");
//    }

    /**
     * 用户是否已经登录
     */
    public boolean isLogin() {
        if (!TextUtils.isEmpty(spUtils.getString("apptoken", ""))) {
            return true;
        }
        return false;
    }

    /**
     * 用户登出
     */
//    public void logout() {
//        spUtils.putString("openid", "");
//    }

    /**
     * MD5加密
     *
     * @return
     */
    public String getMD5Str(String str) {
        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(str.getBytes());
            int i;
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String sortNum(String str) {
        char[] ch = str.toCharArray();
        int[] arr = new int[ch.length];
        for (int i = 0; i < ch.length; i++) {
            arr[i] = Character.getNumericValue(ch[i]);
        }
        Arrays.sort(arr);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            stringBuilder.append(arr[i]);
        }
        return stringBuilder.toString();
    }

    /**
     * 格式化电话号码
     *
     * @param tel
     * @return
     */
    public String parseTel(String tel) {
        if (!TextUtils.isEmpty(tel)) {
            return tel.substring(0, 3) + "***" + tel.substring(7, 11);
        }
        return tel;
        // return "";
    }

    /**
     * 格式化金钱单位
     *
     * @param money
     * @return
     */
    public String formatMoney(int money) {
        BigDecimal l = new BigDecimal(money);
        BigDecimal m = new BigDecimal(10000);
        BigDecimal _money = l.divide(m);
        DecimalFormat decimalFormat;
        if (money % 100 == 0 || money % 10000 == 0) {
            decimalFormat = new DecimalFormat("0.00");
        } else {
            decimalFormat = new DecimalFormat("0.0000");
        }
        return decimalFormat.format(_money.doubleValue());
    }

    /**
     * 格式化金钱单位
     *
     * @param money
     * @return
     */
    public String formatMoney(double money) {
        BigDecimal l = new BigDecimal(money);
        BigDecimal m = new BigDecimal(10000);
        BigDecimal _money = l.divide(m);
        DecimalFormat decimalFormat;
        if (money % 100 == 0 || money % 10000 == 0) {
            decimalFormat = new DecimalFormat("0.00");
        } else {
            decimalFormat = new DecimalFormat("0.0000");
        }
        return decimalFormat.format(_money.doubleValue());
    }

    /**
     * 获取应用版本号
     *
     * @return
     */
    public String getVersionName() {
        return spUtils.getString("versionName", "0.0");
    }

    public void setVersionName(String versionName) {
        spUtils.putString("versionName", versionName);
    }

    public void setStatusBarTranlucent(Window window) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = context.getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.setStatusBarColor(Color.TRANSPARENT);

        }

    }


    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }


}
